<template>
  <div>
    <div v-if="mounted">
      <FormRender
        ref="formRenderRef"
        v-model:config="formJson"
        v-model="formData"
      />
    </div>
    <footer class="el-dialog__footer">
      <span class="dialog-footer">
        <el-button
          v-loading="loading"
          type="warning"
          @click="close"
          icon="Close"
          >关闭</el-button
        >
        <el-button
          type="info"
          :disabled="loading"
          v-loading="loading"
          icon="Folder"
          @click="saveFlow"
        >
          暂存草稿
        </el-button>
        <el-button
          v-loading="loading"
          type="primary"
          :disabled="loading"
          icon="Check"
          @click="startFlow"
        >
          发起工单
        </el-button>
      </span>
    </footer>
  </div>
</template>

<script setup lang="ts" name="OrderStartForm">
import { getObj, saveStart, saveCraft } from "@/api/flow/orderinst";
import { parseWithFunctions } from "@/flow";
import { ref } from "vue";
import { useMessage } from "@/hooks/message";
import { validateNull } from "@/utils/validate";
import FormRender from "@/views/design/form/FormRender.vue";

const emits = defineEmits(["close", "saved", "started"]);

const props = defineProps({
  form: {
    type: Object,
    default: {
      id: "",
      formName: "",
      formInfo: null,
      printInfo: null,
      formData: null,
      componentUrl: ""
    }
  },
  formData: {
    type: String,
    default: null
  },
  order: {
    type: Object,
    default: {
      id: "",
      orderId: "",
      orderInstCode: "",
      defFlowId: "",
      flowKey: "",
      formId: ""
    }
  }
});

const formRenderRef = ref(null);
const loading = ref(false);
const formData = ref(null);
const mounted = ref(false);
const tableListRefs = ref<any>({});
const componentRefs = ref<any>({});
provide("componentRefs", componentRefs);
provide("tableListRefs", tableListRefs);

watchEffect(async () => {
  if (props.order.id) {
    getObj(props.order.id).then(res => {
      if (res.code === 200) {
        if (res.data.formData) {
          const data = parseWithFunctions(res.data.formData);
          formData.value = data;
        }
      }
    });
  }
  mounted.value = true;
});

const formJson = computed(() => {
  if (props.form && props.form.formInfo) {
    let formInfo = parseWithFunctions(props.form.formInfo);
    return formInfo;
  } else {
    return {
      conf: {
        labelPosition: "right", //标签位置
        labelWidth: 80, //标签宽度，
        size: "default"
      },
      components: []
    };
  }
});

const close = () => {
  emits("close");
};

async function saveFlow() {
  loading.value = true;
  formRenderRef.value
    .validateForm()
    .then(valid => {
      if (valid) {
        let formData = formRenderRef.value.getFormData();
        if (validateNull(formData)) {
          useMessage().warning("请输入表单信息");
          return;
        }
        const params = {
          id: props.order.id,
          orderId: props.order.orderId,
          flowKey: props.order.flowKey,
          defFlowId: props.order.defFlowId,
          formId: props.form.id,
          status: "-2",
          formData: JSON.stringify(formData)
        };
        saveCraft(params).then(res => {
          if (res.code === 200) {
            useMessage().success("工单保存成功");
            emits("saved");
          } else {
            useMessage().error(res.msg);
          }
        });
      }
      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
}

async function startFlow() {
  loading.value = true;
  formRenderRef.value
    .validateForm()
    .then(valid => {
      if (valid) {
        let formData = formRenderRef.value.getFormData();
        if (validateNull(formData)) {
          useMessage().warning("请输入表单信息");
          return;
        }
        const params = {
          id: props.order.id,
          orderId: props.order.orderId,
          flowKey: props.order.flowKey,
          defFlowId: props.order.defFlowId,
          orderInstCode: props.order.orderInstCode,
          formId: props.form.id,
          status: "-1",
          formData: JSON.stringify(formData)
        };
        saveStart(params).then(res => {
          if (res.code === 200) {
            useMessage().success("工单发起成功");
            emits("started");
          } else {
            useMessage().success(res.msg);
          }
        });
      }
      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
}
</script>

<style lang="scss" scoped>
.el-dialog__footer {
  padding-top: 0px !important;
  text-align: center;

  .dialog-footer {
    text-align: center;
  }
}
</style>
